package o.json;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

/**
 * JSON Writer 2
 * @author per.a.engstrom
 *
 */
public class JSONWriter2 extends JSONWriter {
	private int indent = 0;

	public JSONWriter2() {
		super();
	}
	public JSONWriter2(Writer writer) {
		super(writer);
	}

	@Override
	public void writeObject(JSONObject object) throws IOException {
//		buffer.append("{\n");
		writer.append("{\n");
		indent++;

		final Iterator<JSONString> iterator = object.getKeys().iterator();
		while (iterator.hasNext()) {
			final JSONString key = iterator.next();
			final JSONValue value = object.getValue(key);
//			for (int i = 0; i < indent; ++i) buffer.append("\t");
			for (int i = 0; i < indent; ++i) writer.append("\t");

			write(key);
//			buffer.append(":");
			writer.append(":");
			write(value);

//			if (iterator.hasNext()) buffer.append(",");
			if (iterator.hasNext()) writer.append(",");
//			buffer.append("\n");
			writer.append("\n");
		}

		indent--;
//		for (int i = 0; i < indent; ++i) buffer.append("\t");
		for (int i = 0; i < indent; ++i) writer.append("\t");
//		buffer.append("}");
		writer.append("}");
	}

	@Override
	public void writeArray(JSONArray array) throws IOException {
//		buffer.append("[\n");
		writer.append("[\n");
		indent++;

		final Iterator<JSONValue> iterator = array.iterator();
		while (iterator.hasNext()) {
			final JSONValue value = iterator.next();
//			for (int i = 0; i < indent; ++i) buffer.append("\t");
			for (int i = 0; i < indent; ++i) writer.append("\t");

			write(value);

//			if (iterator.hasNext()) buffer.append(",");
			if (iterator.hasNext()) writer.append(",");
//			buffer.append("\n");
			writer.append("\n");
		}

		indent--;
//		for (int i = 0; i < indent; ++i) buffer.append("\t");
		for (int i = 0; i < indent; ++i) writer.append("\t");
//		buffer.append("]");
		writer.append("]");
	}
}
